package com.iyitong.account;

import net.sf.json.JSONObject;

import com.iyitong.account.entity.Account;
import com.iyitong.account.service.AccountService;
import com.iyitong.common.BaseAction;
import com.iyitong.common.util.MD5Util;

public class AccountAction extends BaseAction {

	private static final long serialVersionUID = 5395264313730814281L;
	
	private AccountService accountService;
	
	public String reg() {
		JSONObject json = new JSONObject();
		String name = getParameter("account");
		String email = getParameter("email");
		String password = MD5Util.getMD5(getParameter("password"));
		Account account = new Account();
		account.setAccount(name);
		account.setEmail(email);
		account.setPassword(password);
		try {
			accountService.createAccount(account);
			json.put("result", SUCCESS);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			json.put("error", e.getMessage());
		}
		writeJosnObject(json);
		return SUCCESS;
	}
	
	public String login() {
		JSONObject json = new JSONObject();
		String name = getParameter("account");
		String password = MD5Util.getMD5(getParameter("password"));
		Account account = new Account();
		account.setAccount(name);
		account.setPassword(password);
		try {
			account = accountService.validateAccount(account);
			if(account == null) {
				addFieldError("account", "用户名或密码错误!");
				return NONE;
			} else
				json.put("result", SUCCESS);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			json.put("error", e.getMessage());
		}
		writeJosnObject(json);
		return SUCCESS;
	}
	
	public String check() {
		String name = getParameter("account");
		String email = getParameter("email");
		String type = getParameter("type");
		Account account = new Account();
		if("account".equals(type))
			account.setAccount(name);
		else
			account.setEmail(email);
		try {
			account = accountService.checkAccount(account);
			if(account == null)
				writeString("N");
			else
				writeString("Y");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ERROR;
		}
		return null;
	}

	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}
}